<?php

namespace Home\DAO;

use Home\Service\IdGenService;
use Home\Service\UserService;
use Think\Template\Driver\Mobile;

/**
 * 快递员 DAO
 *
 * @author 李静波
 */
class ExpressManDAO extends PSIBaseDAO {
	private $LOG_CATEGORY = "快递员管理";

	/**
	 * 新增或编辑用户
	 */
	public function editExpressMan($params) {
		$id = $params["id"];
		$name = $params["name"];
		$mobile = $params["mobile"];
		$bindCode = $params["bindCode"];
		$enabled = $params["enabled"];
		$districtList = $params["districtList"];
		$py = $params["py"];
		
		$db = M();
		
		$db->startTrans();
		
		if (! $bindCode) {
			$bindCode = $mobile;
		}
		
		$idGen = new IdGenService();
		
		$us = new UserService();
		$dataOrg = $us->getLoginUserDataOrg();
		$companyId = $us->getCompanyId();
		
		$log = null;
		if ($id) {
			// 编辑
			
			// 检查快递员是否已经存在
			$sql = "select count(*) as cnt
					from t_express_man
					where mobile = '%s' and id <> '%s' ";
			$data = $db->query($sql, $mobile, $id);
			$cnt = $data[0]["cnt"];
			if ($cnt > 0) {
				$db->rollback();
				return $this->bad("手机号为[$mobile]的快递员已经存在");
			}
			// 检查校验码是否唯一
			$sql = "select count(*) as cnt from t_express_man
					where bind_code = '%s' and id <> '%s' ";
			$data = $db->query($sql, $bindCode, $id);
			$cnt = $data[0]["cnt"];
			if ($cnt > 0) {
				$db->rollback();
				return $this->bad("校验码[{$bindCode}]已经存在，请重新输入");
			}
			
			$sql = "update t_express_man
					set name = '%s', mobile = '%s', bind_code = '%s',
						enabled = %d, py = '%s'
					where id = '%s' ";
			$rc = $db->execute($sql, $name, $mobile, $bindCode, $enabled, $py, $id);
			if ($rc === false) {
				$db->rollback();
				return $this->sqlError(__LINE__);
			}
			
			$log = "编辑快递员[姓名 = {$name} , 手机号 = {$mobile}]";
		} else {
			// 新增
			$id = $idGen->newId($db);
			
			// 检查快递员是否已经存在
			$sql = "select count(*) as cnt 
					from t_express_man 
					where mobile = '%s' ";
			$data = $db->query($sql, $mobile);
			$cnt = $data[0]["cnt"];
			if ($cnt > 0) {
				$db->rollback();
				return $this->bad("手机号为[$mobile]的快递员已经存在");
			}
			
			// 检查校验码是否唯一
			$sql = "select count(*) as cnt from t_express_man
					where bind_code = '%s' ";
			$data = $db->query($sql, $bindCode);
			$cnt = $data[0]["cnt"];
			if ($cnt > 0) {
				$db->rollback();
				return $this->bad("校验码[{$bindCode}]已经存在，请重新输入");
			}
			
			$sql = "insert into t_express_man (id, name, mobile, bind_code, enabled,
						data_org, company_id, py)
					values ('%s', '%s', '%s', '%s', %d, '%s', '%s', '%s')";
			$rc = $db->execute($sql, $id, $name, $mobile, $bindCode, $enabled, $dataOrg, $companyId, 
					$py);
			if ($rc === false) {
				$db->rollback();
				return $this->sqlError(__LINE__);
			}
			
			$log = "新增快递员[姓名 = {$name} , 手机号 = {$mobile}]";
		}
		
		// 快递员所属片区
		$sql = "delete from t_express_man_district
				where express_man_id = '%s' ";
		$db->execute($sql, $id);
		
		$list = explode(",", $districtList);
		foreach ( $list as $districtId ) {
			// 检查区域id是否存在
			$sql = "select count(*) as cnt from t_district where id = '%s' ";
			$data = $db->query($sql, $districtId);
			$cnt = $data[0]["cnt"];
			if ($cnt == 0) {
				continue;
			}
			
			// 检查该片区是否已经属于该快递员了
			$sql = "select count(*) as cnt from t_express_man_district
						where express_man_id = '%s' and district_id = '%s' ";
			$data = $db->query($sql, $id, $districtId);
			$cnt = $data[0]["cnt"];
			if ($cnt > 0) {
				continue;
			}
			
			// 插入新片区
			$sql = "insert into t_express_man_district (id, express_man_id, district_id)
						values ('%s', '%s', '%s')";
			$rc = $db->execute($sql, $idGen->newId($db), $id, $districtId);
			if ($rc === false) {
				$db->rollback();
				return $this->sqlError(__LINE__);
			}
		}
		
		// 记录业务日志
		if ($log) {
			$bl = new BizlogDAO($db);
			$bl->insertBizlog($log, $this->LOG_CATEGORY);
		}
		
		$db->commit();
		
		return $this->ok($id);
	}

	/**
	 * 快递员列表
	 */
	public function expressManList($params) {
		$name = $params["name"];
		$mobile = $params["mobile"];
		$status = $params["status"];
		
		$db = M();
		
		$queryParamas = array();
		$sql = "select id, name, mobile, wx_id, bind_code, enabled
				from t_express_man 
				where (1 = 1)";
		if ($name) {
			$sql .= " and (name like '%s')";
			$queryParamas[] = "%$name%";
		}
		
		if ($mobile) {
			$sql .= " and (mobile like '%s')";
			$queryParamas[] = "%$mobile%";
		}
		if ($status != - 1) {
			$sql .= "and (enabled = %d)";
			$queryParamas[] = $status;
		}
		
		$sql .= " order by name";
		$data = $db->query($sql, $queryParamas);
		$result = array();
		foreach ( $data as $v ) {
			$item = array(
					"id" => $v["id"],
					"name" => $v["name"],
					"mobile" => $v["mobile"],
					"wxId" => $v["wx_id"],
					"bindCode" => $v["bind_code"],
					"status" => $v["enabled"]
			);
			
			// 片区
			$sql = "select d.name
				from t_express_man_district e, t_district d
				where e.express_man_id = '%s'
					and e.district_id = d.id
				order by d.name ";
			$d = $db->query($sql, $v["id"]);
			$districtArray = array();
			foreach ( $d as $t ) {
				$districtArray[] = $t["name"];
			}
			
			$item["district"] = implode(",", $districtArray);
			
			$result[] = $item;
		}
		
		$queryParamas = array();
		$sql = "select count(*) as cnt
				from t_express_man
				where (1 = 1)";
		if ($name) {
			$sql .= " and (name like '%s')";
			$queryParamas[] = "%$name%";
		}
		
		if ($mobile) {
			$sql .= " and (mobile like '%s')";
			$queryParamas[] = "%$mobile%";
		}
		if ($status != - 1) {
			$sql .= "and (enabled = %d)";
			$queryParamas[] = $status;
		}
		
		$data = $db->query($sql, $queryParamas);
		$cnt = $data[0]["cnt"];
		
		return array(
				"dataList" => $result,
				"totalCount" => $cnt
		);
	}

	/**
	 * 删除快递员
	 */
	public function deleteExpressMan($params) {
		$id = $params["id"];
		
		$db = M();
		
		$db->startTrans();
		
		$sql = "select name, mobile from t_express_man where id = '%s' ";
		$data = $db->query($sql, $id);
		if (! $data) {
			$db->rollback();
			return $this->bad("要删除的快递员不存在");
		}
		
		$name = $data[0]["name"];
		$mobile = $data[0]["mobile"];
		
		// 判断是否可以删除该快递员
		$sql = "select count(*) as cnt 
				from t_express_bill
				where rec_courier_user_id = '%s' or send_courier_user_id = '%s' ";
		$data = $db->query($sql, $id, $id);
		$cnt = $data[0]["cnt"];
		if ($cnt > 0) {
			$db->rollback();
			return $this->bad("要删除的快递员[姓名：{$name}，手机：{$mobile}]已经在运单中使用了，不能删除");
		}
		
		// 删除
		$sql = "delete from t_express_man_district where express_man_id = '%s' ";
		$rc = $db->execute($sql, $id);
		if ($rc === false) {
			$db->rollback();
			return $this->sqlError(__LINE__);
		}
		
		$sql = "delete from t_express_man where id = '%s' ";
		$rc = $db->execute($sql, $id);
		if ($rc === false) {
			$db->rollback();
			return $this->sqlError(__LINE__);
		}
		
		// 记录业务日志
		$log = "删除快递员(姓名 = {$name}， 手机 = {$mobile})";
		$bs = new BizlogDAO($db);
		$bs->insertBizlog($log, $this->LOG_CATEGORY);
		
		$db->commit();
		
		return $this->ok();
	}

	public function expressManDistrict($params) {
		$id = $params["id"];
		
		$db = M();
		$sql = "select d.id, d.name
				from t_express_man_district e, t_district d
				where e.express_man_id = '%s' 
					and e.district_id = d.id
				order by d.name ";
		
		$data = $db->query($sql, $id);
		
		$result = array();
		foreach ( $data as $v ) {
			$item = array(
					"id" => $v["id"],
					"name" => $v["name"]
			);
			
			$result[] = $item;
		}
		
		return $result;
	}

	/**
	 * 获得某个快递员的信息
	 */
	public function expressManInfo($params) {
		$db = M();
		
		$id = $params["id"];
		$result = array();
		
		$sql = "select name, mobile, enabled 
				from t_express_man 
				where id = '%s' ";
		$data = $db->query($sql, $id);
		if (! $data) {
			return $result;
		}
		
		$v = $data[0];
		$result["name"] = $v["name"];
		$result["mobile"] = $v["mobile"];
		$result["enabled"] = $v["enabled"];
		
		// 片区
		$sql = "select d.id, d.name
				from t_express_man_district e, t_district d
				where e.express_man_id = '%s' and e.district_id = d.id
				order by d.name ";
		$items = array();
		$data = $db->query($sql, $id);
		foreach ( $data as $v ) {
			$item = array(
					"id" => $v["id"],
					"name" => $v["name"]
			);
			$items[] = $item;
		}
		$result["districtList"] = $items;
		
		return $result;
	}

	public function queryData($params) {
		$db = M();
		
		$queryKey = $params["queryKey"];
		if ($queryKey == null) {
			$queryKey = "";
		}
		
		$sql = "select id, name, mobile
				from t_express_man
				where (name like '%s' or py like '%s'
					or mobile like '%s') and enabled = 1
				order by name limit 20 ";
		$queryParams = array();
		$key = "%{$queryKey}%";
		$queryParams[] = $key;
		$queryParams[] = $key;
		$queryParams[] = $key;
		
		return $db->query($sql, $queryParams);
	}
}